CC_FW.modules.Form = Class.extend({
    col_fields: null,
    formView : null,
    formModel : null,
    ident : null,
    fields : null,
    isMultipart : null,
    action : null,
    method : null,
    buttons : null,
    events : {
        'submit' : this.doSubmit
    },
    init : function(ident, action, method, isMultipart, events, fields, buttons) {
        this.method = typeof method != 'undefined' && method != null ? method : 'GET';
        this.ident = typeof ident != 'undefined' && ident != null ? ident : new Date().getTime().toString();
        this.isMultipart = typeof isMultipart != 'undefined' && isMultipart != null ? isMultipart : false;
        this.action = typeof action != 'undefined' && action != null ? action : '#';
        this.events = typeof events != 'undefined' && events != null ? events : {};
        this.buttons = typeof buttons != 'undefined' && buttons != null ? buttons : new Array();
        this.fields = typeof fields != 'undefined' && fields != null ? fields : new Array();
        //this.col_fields = new CC_FW.modules.FormObjects.col_form_fields();
        this._setFormModel();
        this._setFormView();
    },
    _setFormModel : function() {
        this.formModel = new CC_FW.modules.FormObjects.mod_form({
            name : this.ident,
            action : this.action,
            elemid : this.ident,
            name : this.ident,
            multipart : this.isMultipart
        });
    },

    _setFormView : function() {
        this.formView = new CC_FW.modules.FormObjects.vie_form({
            model : this.formModel,
            collection : {fields: this.fields, buttons: this.buttons, events: this.events}
        });
    },

    _setFields : function() {
        for (var i = 0; i < this.fields.length; i++) {
            this.setField(this.fields[i]);
        }
    },
    setField : function(mod_field) {
        this.col_fields.add(new CC_FW.modules.FormObjects.mod_form_field(mod_field));
    },
    submitRequest : function() {
        this.events.onSubmit();
    },
    getValues : function() {

    },
    getForm : function() {
        return this.formView;
    }
});

CC_FW.modules.FormObjects  = {};

//models
CC_FW.modules.FormObjects.mod_form = Backbone.Model.extend({
    defaults : {
        name : 'generic-form-' + (new Date().getTime()).toString(),
        action : '#',
        elemid : 'generic-form-' + (new Date().getTime()).toString(),
        multipart : false,
        method : 'GET'
    }
});

CC_FW.modules.FormObjects.mod_form_field = Backbone.Model.extend({
    defaults : {
        'type' : 'text',
        'value' : '',
        'elemid' : 'generic-field-' + (new Date().getTime()).toString(),
        'name' : 'generic-field-' + (new Date().getTime()).toString(),
        'label' : 'generic-label'
    },
    initialize : function() {

    }
});

CC_FW.modules.FormObjects.mod_input = Backbone.Model.extend({
    defaults : {
        "type" : 'text',
        "elemid" : 'generic-text-input-' + (new Date().getTime()).toString(),
        "name" : 'generic-text-input-' + (new Date().getTime()).toString(),
        "value" : '',
        "maxlength" : 100,
        'label' : 'generic-label'
    }
});

CC_FW.modules.FormObjects.mod_textarea = Backbone.Model.extend({
    defaults : {
        "elemid" : 'generic-text-area-' + (new Date().getTime()).toString(),
        "name" : 'generic-text-area-' + (new Date().getTime()).toString(),
        "value" : '',
        "maxlength" : 600,
        'label' : 'generic-label'
    }
});

CC_FW.modules.FormObjects.mod_date_mobiscroll = Backbone.Model.extend({
    defaults : {
        elemid : 'generic-mobiscroll-date-' + (new Date().getTime()).toString(),
        name : 'generic-mobiscroll-date-' + (new Date().getTime()).toString(),
        value : '',
        invalid : {},
        theme : 'sense-ui',
        display : 'modal',
        mode : 'mixed',
        animate : 'pop',
        dateOrder : 'mmD ddyy',
        maxlength : 30,
        'label' : 'generic-label'
    }
});

CC_FW.modules.FormObjects.mod_button = Backbone.Model.extend({
    defaults : {
        'elemid' : 'generic-button-' + (new Date().getTime()).toString(),
        'name' : 'generic-button-' + (new Date().getTime()).toString(),
        'label' : 'submit'
    }
});

//collections
CC_FW.modules.FormObjects.col_form_fields = Backbone.Collection.extend({
    model : CC_FW.modules.FormObjects.mod_form_field,
    initialize : function() {
    }
});

//views
CC_FW.modules.FormObjects.vie_form = Backbone.View.extend({
    tagName : 'form',
    fields : {},
    fieldsContainer : null,
    datePickers: new Array(),
    formFields: new Array(),
    events: {
        'click input': 'handleClick',
        'click input[type="submit"]:visible': 'handleSubmit',
        'click input[type="reset"]:visible': 'handleReset'  
    },
    buttons: {},
    initialize : function() {
        this.fields = {};
        this.fieldsContainer = null;
        this.datePickers = new Array();
        this.formFields = new Array();
        $(this.el).html(null);
        this.setAttributes();
        this.setFields();
        this.fieldsContainer = new CC_FW.modules.FormObjects.vie_fields_container_jqm().render().el;
    },
    getValues: function(){
        var values = {};
        for(var fieldName in this.fields){
            if(this.fields.hasOwnProperty(fieldName)){
                values[fieldName] = this.fields[fieldName].getValue();
            }
        }
        return values;
    },
    reset: function(){
        this.$el.find('input[type="reset"]:hidden').click();
    },
    handleSubmit: function(ev){
        //ev.preventDefault();
        this.collection.events['submit'](this, ev);
    },
    handleReset: function(ev){
        this.collection.events['cancel'](this, ev);
    },
    handleClick: function(ev){
        var currTarget = $(ev.currentTarget);
        if(currTarget.attr('date-pick') == 'X'){
            var fieldView = this.fields[currTarget.attr('id')];
            fieldView.activate(ev);
        }
    },
    render : function() {
        this.$el.html(this.fieldsContainer);
        for (var fieldId in this.fields) {
            if (this.fields.hasOwnProperty(fieldId)) {
                var formField = this.fields[fieldId];
                $(this.fieldsContainer).append(formField.render().el);
                //this.formFields.push(formField);
            }
        }
            
        var buttonsCont = $('<li class="ui-body ui-body-b"></li>');
        var buttonsGrid = $('<fieldset class="ui-grid-a"></fieldset>');
        var cancelButton = $('<div class="ui-block-a"></div>').append($('<input data-theme="a" type="reset" value="cancel" />'));
        var submitButton = $('<div class="ui-block-b"></div>').append($('<input data-theme="a" type="submit" value="submit" />'));
        //hack
        var hiddenCancel = $('<div class="ui-block-a"></div>').append($('<input type="reset" value="hidden reset" />')).hide();
        buttonsGrid.append(cancelButton);
        buttonsGrid.append(submitButton);
        buttonsCont.append(buttonsGrid);
        buttonsCont.append(hiddenCancel);
        
        $(this.fieldsContainer).append(buttonsCont);
        this.$el.html(this.fieldsContainer);
        return this;
    },
    setButtons: function(){
        for(var i=0, buttonsLen = this.collection.buttons.length, buttons = this.collection.buttons;i<buttonsLen;i++){
            var buttonJson = buttons[i];
            var buttonModel = new CC_FW.modules.FormObjects.mod_button(buttonJson);
            this.fields[fieldJson.id] = new CC_FW.modules.FormObjects.vie_({
                model : buttonModel
            });
        }
    },
    setFields : function() {
        for (var i = 0, fieldsLen = this.collection.fields.length, fields = this.collection.fields; i < fieldsLen; i++) {
            var fieldJson = fields[i];
            var fieldModel = null;
            var fieldView = null;
            switch(fieldJson.elem) {
                case 'input':
                    switch(fieldJson.type) {
                        case 'date':
                            fieldModel = new CC_FW.modules.FormObjects.mod_date_mobiscroll({
                                elemid : fieldJson.id,
                                name : fieldJson.id,
                                value : fieldJson.value,
                                label : fieldJson.label
                            });
                            fieldView = CC_FW.modules.FormObjects.vie_date_mobiscroll;
                            break;

                        case 'text':
                            fieldModel = new CC_FW.modules.FormObjects.mod_input({
                                "type" : 'text',
                                "elemid" : fieldJson.id,
                                "name" : fieldJson.id,
                                "value" : fieldJson.value,
                                label : fieldJson.label
                            });
                            fieldView = CC_FW.modules.FormObjects.vie_input;
                            break;

                        case 'number':
                            fieldModel = new CC_FW.modules.FormObjects.mod_input({
                                "type" : 'number',
                                "elemid" : fieldJson.id,
                                "name" : fieldJson.id,
                                "value" : fieldJson.value,
                                label : fieldJson.label
                            });
                            fieldView = CC_FW.modules.FormObjects.vie_input;
                            break;
                    }
                    break;

                case 'textarea':
                    fieldModel = new CC_FW.modules.FormObjects.mod_textarea({
                        "elemid" : fieldJson.id,
                        "name" : fieldJson.id,
                        "value" : fieldJson.value,
                        label : fieldJson.label
                    });
                    fieldView = CC_FW.modules.FormObjects.vie_textarea;
                    break;

                default:
                    fieldModel = new CC_FW.modules.FormObjects.mod_input({
                        "type" : fieldJson.type,
                        "id" : fieldJson.id,
                        "name" : fieldJson.id,
                        "value" : fieldJson.value,
                        label : fieldJson.label
                    });
                    fieldView = CC_FW.modules.FormObjects.vie_input;
                    break;
            }

            this.fields[fieldJson.id] = new fieldView({
                model : fieldModel
            });
        }
        return false;
    },
    setAttributes : function() {
        var el = $(this.el);
        var formModelJson = this.model.toJSON();
        el.attr('name', formModelJson.name);
        el.attr('action', formModelJson.action);
        el.attr('method', formModelJson.method);
        el.attr('id', formModelJson.elemid);
        if (formModelJson.multipart == true) el.attr('enctype', "multipart/form-data");
    }
});

CC_FW.modules.FormObjects.vie_fields_container_jqm = Backbone.View.extend({
    tagName : 'ul',
    attributes : {
        'data-role' : 'listview',
        'data-inset': 'true'
    },
    initialize : function() {
        $(this.el).html(null);
    },
    render : function() {
        $(this.el).attr('data-role', 'listview');
        $(this.el).attr('data-inset', 'false');
        return this;
    }
});

CC_FW.modules.FormObjects.vie_field_container_jqm = Backbone.View.extend({
    tagName : 'li',
    attributes : {
        'data-role' : 'fieldcontain'
    },
    initialize : function() {
        
    },
    render : function() {
        return this;
    }
});

CC_FW.modules.FormObjects.vie_field_label = Backbone.View.extend({
    tagName : 'label',
    label : 'no label',
    attributes : {},
    fieldId: null,
    initialize : function(options) {
        $(this.el).html(null);
        this.fieldId = options.fieldId;
        this.label = options.label;
    },
    render : function() {
        $(this.el).attr('for', this.fieldId);
        $(this.el).html(this.label);
        return this;
    }
});

CC_FW.modules.FormObjects.vie_input = Backbone.View.extend({
    tagName : 'li',
    label : null,
    input : null,
    attributes : {
        'data-role' : 'fieldcontain'
    },
    initialize : function() {
        $(this.el).html(null);
        var modelJson = this.model.toJSON();
        this.label = new CC_FW.modules.FormObjects.vie_field_label({
            fieldId : modelJson.elemid,
            label : modelJson.label
        }).render().el;
        this.input = $('<input></input>').attr('id', modelJson.elemid).attr('type', modelJson.type).attr('maxlength', modelJson.maxlength).attr('name', modelJson.elemid).val(modelJson.value);
    },
    render : function() {
        $(this.el).attr('id', 'field-container_' + this.model.toJSON().elemid);
        $(this.el).html(this.label);
        $(this.el).append(this.input);
        return this;
    },
    getValue: function(){
        return this.input.val();
    }
});

CC_FW.modules.FormObjects.vie_textarea = Backbone.View.extend({
    tagName : 'li',
    label : null,
    input : null,
    attributes : {
        'data-role' : 'fieldcontain'
    },
    initialize : function() {
        $(this.el).html(null);
        var modelJson = this.model.toJSON();
        this.label = new CC_FW.modules.FormObjects.vie_field_label({
            fieldId : modelJson.elemid,
            label : modelJson.label
        }).render().el;
        this.input = $('<textarea></textarea>').attr('id', modelJson.elemid).attr('type', modelJson.type).attr('maxlength', modelJson.maxlength).attr('name', modelJson.elemid).val(modelJson.value);
    },
    render : function() {
        $(this.el).attr('id', 'field-container_' + this.model.toJSON().elemid)
        $(this.el).html(this.label);
        $(this.el).append(this.input);
        return this;
    },
    getValue: function(){
        return this.input.val();
    }
});

CC_FW.modules.FormObjects.vie_date_mobiscroll = Backbone.View.extend({
    tagName : 'li',
    attributes : {
        'data-role' : 'fieldcontain'
    },
    activated: false,
    input: null,
    initialize : function() {
        $(this.el).html(null);
        var modelJson = this.model.toJSON();
        this.label = new CC_FW.modules.FormObjects.vie_field_label({
            fieldId : modelJson.elemid,
            label : modelJson.label
        }).render().el;
        this.input = $('<input></input>').attr('date-pick', 'X').attr('id', modelJson.elemid).attr('type', 'text').attr('maxlength', modelJson.maxlength).attr('name', modelJson.elemid).val(modelJson.value);
        //this.events['click ' + 'input#' + modelJson.elemid] = 'handleClick';
        /*
        $(this.input).on('click', function(ev){
            that.handleClick(ev);
        })
        */
    },
    render : function() {
        $(this.el).attr('id', 'field-container_' + this.model.toJSON().elemid)
        $(this.el).html(this.label);
        $(this.el).append(this.input);
        return this;
    },
    activate : function(ev) {
        var currTarget = ev.currentTarget;
        //datepicker, check if activated
        if(this.activated == false){
            $(currTarget).mobiscroll().date(this.model.toJSON());
            this.activated = true;
        }
        $(currTarget).mobiscroll('show');
        // $(currTarget).click(function() {
            // $(this).mobiscroll('show');
            // return false;
        // });
        return false;
    },
    getValue: function(){
        //return this.$el.mobiscroll('getDate');
        return Date.parse($(this.el).find('input#' + this.model.get('elemid')).val());
    }
});

//autocomplete from here
//http://uglymongrel.com/jqm/faq/docs/demos/listviews/listview-filter-autocomplete.html#&ui-state=dialog
               
